package db

import (
	"gitee.com/Hu-Lyndon/distill-resk/infra"
	_ "github.com/go-sql-driver/mysql"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/dbx"
	"github.com/tietang/props/kvs"
)

// dbx 数据库实例
var database *dbx.Database

func DbxDatabase() *dbx.Database {
	return database
}

// dbx数据库starter，并且设置为全局
type DbxDatabaseStarter struct {
	infra.BaseStarter
}

// 数据库的实例化启动生命周期晚于配置文件加载，所以放到Setup中
func (s *DbxDatabaseStarter) Setup(ctx infra.StarterContext) {
	var err error
	conf := ctx.Props()
	// 数据库配置
	settings := dbx.Settings{}
	err = kvs.Unmarshal(conf, &settings, "mysql")
	if err != nil {
		panic(err)
	}
	log.Infof("%+v", settings)
	log.Info("mysql conn url:", settings.DataSourceName())
	database, err = dbx.Open(settings)
	if err != nil {
		panic(err)
	}
	log.Info(database.Ping())

}
